package br.com.bcc481.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.hibernate.Session;
import org.hibernate.exception.ConstraintViolationException;

import br.com.bcc481.models.Tarefa;
import br.com.bcc481.models.Usuario;

public class HibernateTarefaDAO {

	public static void addTarefa(Tarefa tarefa, Usuario usuario) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager em = factory.createEntityManager();

		try{
			em.getTransaction().begin();    
			em.persist(tarefa);
			em.getTransaction().commit();
		}catch(ConstraintViolationException e){
			e.printStackTrace();
		}
		
		em.close();

		factory.close();
	}


	public static List<Tarefa> getListaTarefa(Long chave) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager manager = factory.createEntityManager();

		//cuidado, use o import javax.persistence.Query
		Query query = manager.createQuery("from Tarefa where usuario_id = "  + chave );

		List<Tarefa> lista = query.getResultList();

		if (lista != null) {
			manager.close();
			return lista;
		}
		else
			return null;
		
	}
	
	
	public static Tarefa pesquisaTarefaPorId(Long chave) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager manager = factory.createEntityManager();

		//cuidado, use o import javax.persistence.Query
		Query query = manager.createQuery("from Tarefa where id = "+ "'" + chave + "'");

		List<Tarefa> lista = (List<Tarefa>) query.getResultList();

		if (lista.size() >  0) {
			manager.close();
			return lista.get(0);
		}
		else
			return null;
		
	}
	

	public static int removeTarefa(Long chave) {

		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager em = factory.createEntityManager();
		
		Tarefa tarefa = new Tarefa();
		tarefa = pesquisaTarefaPorId(chave);

		//CASO ENCONTRE ALGUMA TAREFA, DELETA DO BANCO
		if (tarefa != null) {

			em.getTransaction().begin();
			Object c = em.merge(tarefa);
			em.remove(c);
			em.getTransaction().commit();
			em.close();
			
			return 1;
		}
		else {
			return 0;
		}
	}
	
	
	public static int atualizaTarefa(Tarefa tarefa) {
		
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("rosalgad_bcc481bd");
		EntityManager em = factory.createEntityManager();

		em.getTransaction().begin();
		em.merge(tarefa);
		em.getTransaction().commit();
		
		return 1;
	}
	
}